package com.mapre.instance.friend;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

/**
 * @author shengtao
 * @Description: mapper-reducer
 * @date 2019/01/14 17:46
 */
public class FriendMR extends Configured implements Tool{

    public static void main(String args[]) throws Exception {
        ToolRunner.run(new FriendMR(),args);
        System.out.println("map reducer processed success!");
    }

    @Override
    public int run(String[] args) throws Exception {
        String nameNodeUrl = "hdfs://192.168.220.135:9000";
        String nameNodeName = "fs.defaultFS";
        Configuration configuration = new Configuration();
        configuration.set(nameNodeName, nameNodeUrl);
        Job job = Job.getInstance(configuration);
        job.setJarByClass(FriendMR.class);

        job.setMapperClass(FirstMapper.class);
        job.setReducerClass(FirstReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.setInputPaths(job,new Path(args[0]));
        FileOutputFormat.setOutputPath(job,new Path(args[1]));

        FileInputFormat.setInputPaths(job,new Path(args[0]));
        FileOutputFormat.setOutputPath(job,new Path(args[1]));

        boolean result = job.waitForCompletion(true);
        if (!result){
            return 1;
        }
        return 0;
    }


    /**
     * A:B,C,D --》 B-A ,C-A,D-A
     *
     * 分散处理
     */
    static class FirstMapper extends Mapper<LongWritable,Text,Text,Text>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String arg[] = line.split(":");

            String user = arg[0];

            String friends = arg[1];
            for (String friend : friends.split(",")){
                context.write(new Text(friend),new Text(user));
            }
        }
    }


    static class FirstReducer extends Reducer<Text,Text,Text,Text>{
        @Override
        protected void reduce(Text friend, Iterable<Text> users, Context context) throws IOException, InterruptedException {
            StringBuilder sb = new StringBuilder();
            for (Text user:users){
                sb.append(user).append(",");
            }
            context.write(friend,new Text(sb.toString()));
        }
    }


}
